<?php
/**
 * Description: 获取直播课堂播放地址
 * User: devforma
 * Date: 15/6/6
 * Time: 23:22
 */

class OpenCourseUrl implements iController {

    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $cmsdb;

        if (validateUser($queryArgs) !== 1 || empty($queryArgs['course_id']) || !is_numeric($queryArgs['course_id'])) {
            return genOutput(1000);
        }

        //课程是否对用户可见
//        if (!$this->isCourseAvailable($queryArgs['user_id'], $queryArgs['course_id'], true))
//            return genOutput(1000);

        //if ($queryArgs['is_open'] === 'true') { //公开课
            //用户是否可见
//            $available = $cmsdb->getVar('SELECT `is_available` FROM `gray_user_open_course` WHERE `user_id`=:uid
//            AND `course_id`=:cid', array(':uid' => $queryArgs['user_id'], ':cid' => $queryArgs['course_id']));
//            if (empty($available))
//                return genOutput(1000);

            //获取课堂信息
            $sql = 'SELECT c.room_id, c.live_platform, c.start_time FROM `data_live_class` AS c INNER JOIN
            `relationship_live_class_and_course` AS r ON c.id=r.class_id AND r.course_id=:course_id LIMIT 1';
            $room = $cmsdb->getRow($sql, array(':course_id' => $queryArgs['course_id']));
/*
        } else { //直播课
            if (empty($queryArgs['class_id']))
                return genOutput(1000);
            //获取课堂信息
            $room = $cmsdb->getRow('SELECT `room_id`, `live_platform` FROM `data_live_class` WHERE `id`=:cid',
                array(':cid' => $queryArgs['class_id']));
        }
*/
        if (empty($room) || empty($room->room_id)) { //课堂信息无效
            return genOutput(1001);
        }

        $nickname = $this->getUserNickname($queryArgs['user_id']); //获取用户昵称

        $isMobile = false;
        if ($queryArgs['terminal_type'] == 'iOS_phone' || $queryArgs['terminal_type'] == 'android_phone'
            || $queryArgs['terminal_type'] == 'mobile_web' || $queryArgs['terminal_type'] == 'hybrid') {
            $isMobile = true;
        }

        //获取播放地址
        $url = $this->getClassUrl($room->room_id, $queryArgs['user_id'], $nickname, $room->live_platform === '多贝云', $isMobile);

        //公开课访问记录
            $this->logEnter($queryArgs['user_id'], $queryArgs['course_id'], $queryArgs['terminal_type'], $room->start_time);

        return empty($url) ? genOutput(1001) : genOutput(1, array('url' => $url));

    }

    /**
     * 公开课进入记录
     * @param int $userId 用户id
     * @param int $courseId 课程id
     * @param string $platform 来源
     * @param string $startTime 课堂开始时间
     */
    private function logEnter($userId, $courseId, $platform, $startTime) {
        global $uddb;

        $exists = $uddb->getVar('SELECT `id` FROM `openclass_enter_log` WHERE `course_id`=:cid AND `user_id`=:uid',
            array(':cid' => $courseId, ':uid' => $userId));

        if (empty($exists)) {
            $uddb->insert('openclass_enter_log', array(
                'user_id' => $userId,
                'course_id' => $courseId,
                'platform' => $platform,
                'enter_time' => date('Y-m-d H:i:s'),
                'course_date' => explode(' ', $startTime)[0]
            ));
        }
    }


    /**
     * 校验用户是否可见课程
     * @param int $userId 用户id
     * @param int $courseId 课程id
     * @param bool $isOpenCourse 是否为公开课
     * @return bool
     */
    private function isCourseAvailable($userId, $courseId, $isOpenCourse) {
        global $cmsdb;

        if ($isOpenCourse) {
            $available = $cmsdb->getVar('SELECT `is_available` FROM `gray_user_open_course` WHERE `user_id`=:uid
            AND `course_id`=:cid', array(':uid' => $userId, ':cid' => $courseId));

        } else {
            $available = $cmsdb->getVar('SELECT `id` FROM `relation_user_product` WHERE `user_id`=:uid
            AND `product_id`=:cid AND `product_type`="zhiboke"', array(
                ':uid' => $userId,
                ':cid' => $courseId
            ));
        }

        return empty($available) ? false : true;
    }


    /**
     * 获取用户昵称
     * @param int $userId 用户id
     * @return string
     */
    function getUserNickname($userId) {
        global $uddb;

        $nickname = $uddb->getVar('SELECT `nickname` FROM `user_social_info` WHERE `user_id`=:user_id',
                array(':user_id' => $userId));

        if (empty($nickname))
            return 'student'.$userId;
	
        return $nickname.'-天天模考App';
    }

    /**
     * 获取课堂进入地址
     * @param string $roomId 房间id
     * @param int $userId 用户id
     * @param string $nickname 用户昵称
     * @param bool $isH5 是否支持H5
     * @param bool $isMobile 是否为移动端
     * @return string
     */
    private function getClassUrl($roomId, $userId, $nickname, $isH5, $isMobile = false) {
        if ($isH5) {
            $api = "http://api.duobeiyun.com/api/v3/room/enter?";
        } else {
            $api = "http://api.jiangzuotong.com/api/v2/room/enter?";
        }

        $params = array(
            'nickname' => trim($nickname),
            'partner' => '20140807101355',
            'roomId' => $roomId,
            'timestamp' => time() * 1000,
            'uid' => $userId,
            'deviceType' => $isMobile ? 2 : 1,
            'userRole' => 2 //2为学生上课地址
        );


        /*****************************************************
         * 生成签名
         */
        ksort($params);

        $paramStr = '';

        foreach($params as $key => $value) {
            $paramStr .= (strval($key).'='.strval($value).'&');
        }
        $sign = md5(rtrim($paramStr, '&').'771f3c17303c49f6a8dc3e3ffbf41990');


        /*****************************************************
         * 构造播放地址
         */
        $paramStr = '';

        foreach($params as $key => $value) {
            $paramStr .= (strval($key).'='.urlencode(strval($value)).'&');
        }

        $paramStr .= ('sign='.$sign);

        return $api.$paramStr;
    }
}
